package com.foocus.foocuscloud.common.aop.transanction;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;

/**
 * Aop事务织入
 *
 * 1.所有方法默认只读事务
 * 2.方法名符合特定条件开头的默认写事务 [ update* / add* / insert* / delete* / ... ]
 */
@Aspect
@Component
@Order(1)
public class TransactionWrapper {

    private  static final Logger LOGGER = LoggerFactory.getLogger(TransactionWrapper.class);

    @Pointcut(value = "execution(* com.springboot.codeminestarter..service.*.*(..))")
    public void transactionPointCut() {

    }

    @After("transactionPointCut()")
    public void aroundTransaction(JoinPoint point) {

        handleTransaction(point);
    }

    private void handleTransaction(JoinPoint point) {

        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();

        Transactional transactional = method.getAnnotation(Transactional.class);
        if (transactional != null) {
            try {
                Propagation propagation = transactional.propagation();
                Isolation isolation = transactional.isolation();
                Class<? extends Throwable>[] classes = transactional.rollbackFor();
                LOGGER.info(">>>>>>> Propagation: {}, Isolation: {}, Throwable: {}", propagation, isolation, classes);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

//        LOGGER.info("事务AOP拦截方法：{}", method);
/*        try {
            method.invoke(annotation);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            LOGGER.info("AOP事务异常：{}", e);
        }*/
    }
}
